package com.example.zx.theline.pub;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zx.theline.R;
import com.loopj.android.http.RequestParams;
import com.scu.miomin.shswiperefresh.view.SHListView;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import GsonBean.ContactBean;
import GsonBean.JhshBean;
import GsonBean.ShenheInfoBean;
import Utils.MyToast;
import app.MyApplication;
import base.BaseActivity;
import dialog.CustomDialog;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

/**
 * Created by Jianqi on 2017\8\16 0016.
 * <p>
 * 查看审核记录的活动页，新增分组，便于查看
 */

public class CheckInfoActivity extends BaseActivity implements View.OnClickListener {
    //UI
    private StickyListHeadersListView mListView;

    TextView leftTextView,centerTextView, cancel,rightTextView;
    RelativeLayout rightLayout;
    //Data
    private List<ShenheInfoBean.ShdwListBean> list;
    private MyAdapter mAdapter;
    private ShenheInfoBean shenheInfoBean;
    //Dialog
    private CustomDialog customDialog; //单位审核用户弹出框
    private TextView cancelBtn, confirmBtn; //监听按钮
    private SHListView mDialogListView;
    private ContactBean contactBean;
    private List<ContactBean.UserListBean> mUserList;
    private DialogAdapter mDialogAdapter;
    //页面传递过来的参数,从列表页点击直接跳转查看
    private String flags = "";
    public static GsonBean.ShyjhxqBean ZsyjhxxShBean;
    public static JhshBean.RowsBean mRowsBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_info);
        Intent intent = getIntent();
        flags = intent.getStringExtra("flags");
        if (flags == null) {
            flags = "";
        }
        InitView();
        InitListen();
        InitData();
    }


    @Override
    protected void InitView() {
        mListView = (StickyListHeadersListView) findViewById(R.id.listview);
        leftTextView = (TextView) findViewById(R.id.leftTextView);
        rightTextView = (TextView) findViewById(R.id.rightTextView);
        centerTextView = (TextView) findViewById(R.id.centerTextView);
        cancel = (TextView) findViewById(R.id.cancel);
        centerTextView.setText("审核信息");
        //初始化自定义Dialog
        customDialog = new CustomDialog(this, R.layout.dialog_dwshyh, R.style.Theme_dialog);
        customDialog.setCanceledOnTouchOutside(false);
        mDialogListView = (SHListView) customDialog.findViewById(R.id.dialog_listview);
        cancelBtn = (TextView) customDialog.findViewById(R.id.btn_cancel);
        confirmBtn = (TextView) customDialog.findViewById(R.id.btn_confirm);
        rightTextView.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void InitData() {
        requestCheckInfoData(); //请求网络数据
    }

    @Override
    protected void InitListen() {
        leftTextView.setOnClickListener(this);
        cancel.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                finish();
                break;
            case R.id.leftTextView:
                finish();
                break;
            case R.id.btn_cancel:
                customDialog.dismiss();
                break;
            case R.id.btn_confirm:
                customDialog.dismiss();
                break;
            default:
                break;
        }
    }

    //请求联系人的数据
    private void requestContactData(int pos) {


        Map<String,String> map=new HashMap<>();
        map.put("ljyyxDwxxId", shenheInfoBean.getShdwList().get(pos).getDwId());
        MyApplication.ShowWaitDialog(this);
        NetWorkApi.getDwContact(map, new Callback<ContactBean>() {
                    @Override
                    public void onResponse(Call<ContactBean> call, Response<ContactBean> response) {
                        try {
                            contactBean = null; //初始化数据，将旧数据清空
                            contactBean = response.body();

                            if (contactBean.getMsg().equals("success")) {
                                if (contactBean.getUserList().size() != 0) {
                                    mUserList = contactBean.getUserList();
                                    mDialogAdapter = new DialogAdapter();
                                    mDialogListView.setAdapter(mDialogAdapter);
                                    customDialog.show();
                                } else {
                                    Toast.makeText(CheckInfoActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                MyToast.showNullObjectError(CheckInfoActivity.this);
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void onFailure(Call<ContactBean> call, Throwable t) {
                        MyToast.showFail();
                        MyApplication.HideWaitDialog();
                    }
                }

        );
    }

    //请求该页面网络数据
    private void requestCheckInfoData() {
        Map<String,String> map=new HashMap<>();
        if (flags.equals("flags")) {
            map.put("jdjhbBh", mRowsBean.getBh());
            map.put("cjrId", mRowsBean.getCjrId());
        } else {
            map.put("jdjhbBh", ZsyjhxxShBean.getInfo().getBh());
            map.put("cjrId", ZsyjhxxShBean.getInfo().getCjrId());
        }
        MyApplication.ShowWaitDialog(this);
        NetWorkApi.getSgyjhshjl(map, new Callback<ShenheInfoBean>() {
                    @Override
                    public void onResponse(Call<ShenheInfoBean> call, Response<ShenheInfoBean> response) {
                        try {
                            shenheInfoBean = null;
                            shenheInfoBean = response.body();
                            if (shenheInfoBean.getMsg().equals("success")) {
                                if (shenheInfoBean.getShdwList().size() != 0) {
                                    list = shenheInfoBean.getShdwList();
                                    if (mAdapter == null) {
                                        mAdapter = new MyAdapter();
                                        mListView.setAdapter(mAdapter);
                                    }
                                } else {
                                    Toast.makeText(CheckInfoActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                MyToast.showNullObjectError(CheckInfoActivity.this);
                            }
                        } catch (Exception e) {
                            MyToast.showFail();
                        }
                        MyApplication.HideWaitDialog();
                    }

                    @Override
                    public void onFailure(Call<ShenheInfoBean> call, Throwable t) {
                        MyToast.showFail();
                    }
                }

        );
    }

    //创建Dialog联系人的适配器
    private class DialogAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mUserList.size();
        }

        @Override
        public Object getItem(int position) {
            return mUserList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder mHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(CheckInfoActivity.this).inflate(R.layout.item_dialog_dwshyh, null);
                mHolder = new ViewHolder();
                mHolder.name = (TextView) convertView.findViewById(R.id.name_key);
                mHolder.phone = (TextView) convertView.findViewById(R.id.phone_value);
                convertView.setTag(mHolder);
            } else {
                mHolder = (ViewHolder) convertView.getTag();
            }
            mHolder.name.setText(mUserList.get(position).getLjyyxWorkerName());
            mHolder.phone.setText(mUserList.get(position).getLjyyxWorkerTel());
            return convertView;
        }

        //ViewHolder类
        class ViewHolder {
            TextView name;
            TextView phone; //施工单位
        }
    }

    //创建内部类，该页面的适配器
    @SuppressWarnings("WeakerAccess")
    class MyAdapter extends BaseAdapter implements StickyListHeadersAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder mHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(CheckInfoActivity.this).inflate(R.layout.adapter_check_info, null);
                mHolder = new ViewHolder();
                mHolder.sgdwKey = (TextView) convertView.findViewById(R.id.sgdw_key);
                mHolder.sgdw = (TextView) convertView.findViewById(R.id.sgdw_value);
                mHolder.isfouty = (TextView) convertView.findViewById(R.id.isnot_agree_value);
                mHolder.shyj = (TextView) convertView.findViewById(R.id.csshyj_value);
                mHolder.riqi = (TextView) convertView.findViewById(R.id.date_time_value);
                mHolder.tbrLayout = (LinearLayout) convertView.findViewById(R.id.tbr_layout);
                mHolder.tbr = (TextView) convertView.findViewById(R.id.tbr_value);
                mHolder.ckdwlxr = (TextView) convertView.findViewById(R.id.scan_contact);
                mHolder.view = convertView.findViewById(R.id.view1);
                convertView.setTag(mHolder);
            } else {
                mHolder = (ViewHolder) convertView.getTag();
            }
            //根据条件判断显示不同审核类型
            if (list.get(position).getDwlb() != null) {
                switch (list.get(position).getDwlb()) {
                    case "sgdw":
                        mHolder.sgdwKey.setText("施工单位:");
                        break;
                    case "jldw":
                        mHolder.sgdwKey.setText("监理单位:");
                        break;
                    case "jsdw":
                        mHolder.sgdwKey.setText("建设单位:");
                        break;
                    case "cwzd":
                        mHolder.sgdwKey.setText("车务站段:");
                        break;
                    case "sbgldw":
                        mHolder.sgdwKey.setText("设备管理单位:");
                        break;
                    case "qtdw":
                        mHolder.sgdwKey.setText("其他单位:");
                        break;
                    case "jsglbm":
                        mHolder.sgdwKey.setText("建设管理部门:");
                        break;
                    case "shcs":
                        mHolder.sgdwKey.setText("审核处室:");
                        break;
                    case "spcs":
                        mHolder.sgdwKey.setText("项目主管部门:");
                        break;
                    case "sgb":
                        mHolder.sgdwKey.setText("施工办:");
                        break;
                    case "tgdw":
                        mHolder.sgdwKey.setText("停工批准单位:");
                        break;
                    default:
                        break;
                }
            }
            //单位名称
            mHolder.sgdw.setText(list.get(position).getDwmc());
            //是否通过，根据条件判断显示对应名称
            if (list.get(position).getSftg() != null) {
                if (ZsyjhxxShBean != null && list.get(position).getSftg().equals("Y") && list.get(position).getDwlb().equals("spcs")
                        && ZsyjhxxShBean.getInfo().getLcstep().equals("99")) {
                    mHolder.isfouty.setText("未提交");
                }

                switch (list.get(position).getSftg()) {
                    case "Y":
                        //同意为绿色
                        mHolder.isfouty.setText("同意");
                        mHolder.isfouty.setTextColor(getResources().getColor(R.color.colorGreenTitle));
                        break;
                    case "N":
                        //不同意为红色
                        mHolder.isfouty.setText("不同意");
                        mHolder.isfouty.setTextColor(getResources().getColor(R.color.colorRed));
                        break;
                    case "YH":
                        mHolder.isfouty.setText("同意并修改");
                        break;
                    case "CH":
                        mHolder.isfouty.setText("撤回");
                        break;
                    case "ZD":
                        mHolder.isfouty.setText("重新指定");
                        break;
                    case "TH":
                        mHolder.isfouty.setText("退回");
                        break;
                    case "ZF":
                        mHolder.isfouty.setText("作废");
                        break;
                    case "HF":
                        mHolder.isfouty.setText("恢复");
                        break;
                    case "TG":
                        mHolder.isfouty.setText("停工");
                        break;
                    default:

                        break;
                }
            } else {
                //默认检查单流程状态字体颜色为蓝色
                mHolder.isfouty.setTextColor(getResources().getColor(R.color.color_llan));
                mHolder.isfouty.setText("未审核");
            }
            //审核意见
            if (list.get(position).getShyj() == null || list.get(position).getShyj().length() == 0) {
                mHolder.shyj.setText("无");
            } else {
                mHolder.shyj.setText(list.get(position).getShyj());
            }
            //创建日期
            if (list.get(position).getShrq() == null || list.get(position).getShrq().length() == 0) {
                mHolder.riqi.setText("无");
            } else {
                mHolder.riqi.setText(list.get(position).getShrq());
            }
            //判断填报人信息是否显示
            String shrInfo = list.get(position).getShrInfo();
            if (shrInfo != null) {
                if (shrInfo.equals("")) {
                    mHolder.tbrLayout.setVisibility(View.GONE);
                    mHolder.view.setVisibility(View.GONE);
                } else {

                    mHolder.tbrLayout.setVisibility(View.VISIBLE);
                    mHolder.view.setVisibility(View.VISIBLE);
                    String[] values = shrInfo.split(","); //按逗号拆分
                    StringBuilder stringBuilder = new StringBuilder();
                    for(int i=0;i<values.length;i++){//将拆分后的字符串拼接起来
                        stringBuilder.append(values[i]);
                        if(i<values.length-1){
                            stringBuilder.append("\n");
                        }
                    }
                    for (String value : values) {

                    }
                    mHolder.tbr.setText(stringBuilder.toString());
                }
            }
            mHolder.ckdwlxr.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //请求联系人数据
                    requestContactData(position);
                }
            });
            return convertView;
        }

        @Override
        public View getHeaderView(int position, View convertView, ViewGroup parent) {
            HeaderViewHolder holder;
            if (convertView == null) {
                holder = new HeaderViewHolder();
                convertView = LayoutInflater.from(CheckInfoActivity.this).inflate(R.layout.item_checkinfo_group, parent, false);
                holder.text = (TextView) convertView.findViewById(R.id.item_text);
                convertView.setTag(holder);
            } else {
                holder = (HeaderViewHolder) convertView.getTag();
            }
            int max = Integer.parseInt(list.get(0).getShzt()); //先把当前最大值取出
            List<Integer> mlist = new ArrayList<>(); //新建源数据集合
            List<Integer> resultList = new ArrayList<>(); //新建反转数据集合
            for (int i = max; i > 0; i--) { //源数据集合整理
                mlist.add(i);
                resultList.add(i);
            }
            Collections.reverse(resultList); //反转结果集
            //展示审核流程记录数据 第一组内容改为 当前审核记录，第二组则 改为历史组别1，依次类推
            if (Integer.parseInt(list.get(position).getShzt()) == max) {
                holder.text.setText("当前审核记录");
            }
            for (int i = 0; i < mlist.size(); i++) {
                if (mlist.get(i) == (Integer.parseInt(list.get(position).getShzt()) + 1)) {
                    holder.text.setText("历史组别" + resultList.get(i));
                }
            }
            return convertView;
        }

        @Override
        public long getHeaderId(int position) {
            return Long.parseLong(list.get(position).getShzt());
        }

        class HeaderViewHolder {
            TextView text;
        }

        //ViewHolder类
        class ViewHolder {
            TextView sgdwKey;
            TextView sgdw; //施工单位
            TextView isfouty; //是否同意
            TextView shyj; //审核意见
            TextView riqi; //日期时间
            LinearLayout tbrLayout; //填报人行
            TextView tbr; //填报人
            TextView ckdwlxr; //查看单位联系人
            View view; //横线
        }
    }

}
